package com.zidian.study.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.mingming.com.library.FlowTagLayout;
import com.mingming.com.library.OnTagSelectListener;
import com.yuyh.library.imgsel.ImageLoader;
import com.yuyh.library.imgsel.ImgSelActivity;
import com.yuyh.library.imgsel.ImgSelConfig;
import com.yuyh.library.imgsel.utils.FileUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;
import com.zidian.student.trucks.R;
import com.zidian.study.adapter.AddQuestionTextAdapter;
import com.zidian.study.adapter.ImagePikerAdapter;
import com.zidian.study.bean.AskClassTags;
import com.zidian.study.event.DeleteImageEvent;
import com.zidian.study.globa.Constant;
import com.zidian.study.globa.ToolBarActivity;
import com.zidian.study.utils.GetUserInfo;
import com.zidian.study.utils.ImageFactory;
import com.zidian.study.utils.ProgressBarBlackUtil;
import com.zidian.study.utils.ToastUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Call;

/**
 * Created by Administrator on 2016/9/3 0003.
 * 添加问题界面
 */
public class InteractionQuestionAddActivity extends ToolBarActivity {
    @Bind(R.id.photo_preview_list_rv)
    RecyclerView photoPreviewListRv;

    private AddQuestionTextAdapter classAdapter;
    private List<String> textTag = new ArrayList<>();
    private FlowTagLayout classTag;
    private EditText problemContent;
    private String issueObject = "";
    private TextView sumbitBtn;

    private static final int REQUEST_CODE = 0;

    private ImagePikerAdapter adapter;
    private List<String> images;
    private ImageFactory imageFactory;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setToolbarView(R.layout.toolbar_evaluate_tags);
        setContentView(R.layout.activity_question_add);
        ButterKnife.bind(this);
        setTitle("提问");
        imageFactory = new ImageFactory();
        images = new ArrayList<>();
        initView();
    }

    public void initView() {
        adapter = new ImagePikerAdapter(this);
        adapter.setImageCount(1);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
        photoPreviewListRv.setLayoutManager(layoutManager);
        photoPreviewListRv.setAdapter(adapter);
        adapter.setOnItemClickListener(new ImagePikerAdapter.OnItemClickListener() {
            @Override
            public void onClick(int position) {
                if (images.size() == position) {
                    pickImages();
                } else {
                    Intent intent = new Intent(context, NewPhotoActivity.class);
                    intent.putExtra("imagePath", images.get(position));
                    intent.putExtra("position", position);
                    startActivity(intent);
                }
            }
        });
        EventBus.getDefault().register(this);

        classAdapter = new AddQuestionTextAdapter(context);
        classTag = (FlowTagLayout) findViewById(R.id.class_tags);
        problemContent = (EditText) findViewById(R.id.problem_content);
        sumbitBtn = (TextView) findViewById(R.id.toolbar_sumbit);

        classTag.setTagCheckedMode(FlowTagLayout.FLOW_TAG_CHECKED_SINGLE);
        classTag.setAdapter(classAdapter);

        getTag();

        classTag.setOnTagSelectListener(new OnTagSelectListener() {
            @Override
            public void onItemSelect(FlowTagLayout parent, List<Integer> selectedList) {

                if (selectedList != null && selectedList.size() > 0) {
                    StringBuilder sb = new StringBuilder();
                    for (int i : selectedList) {
                        sb.append(parent.getAdapter().getItem(i));
                    }

                    issueObject = sb.toString();
//                    Snackbar.make(parent, "选择的标签:" + sb.toString(), Snackbar.LENGTH_LONG)
//                            .setAction("Action", null).show();
                } else {
                    issueObject = "";
//                    Snackbar.make(parent, "没有选择标签", Snackbar.LENGTH_LONG)
//                            .setAction("Action", null).show();
                }

            }
        });

        sumbitBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addQuestion();
            }
        });

    }

    /**
     * 图片加载器
     */
    private ImageLoader loader = new ImageLoader() {
        @Override
        public void displayImage(Context context, String path, ImageView imageView) {
            Glide.with(context).load(path).into(imageView);
        }
    };

    /**
     * 图片选择器
     */
    private void pickImages() {
        ImgSelConfig config = new ImgSelConfig.Builder(loader)
                // 是否多选
                .multiSelect(false)
                // 确定按钮背景色
                .btnBgColor(Color.GRAY)
                // 确定按钮文字颜色
                .btnTextColor(Color.BLUE)
                // 使用沉浸式状态栏
//                .statusBarColor(Color.parseColor("#3F51B5"))
                // 返回图标ResId
                .backResId(android.support.v7.appcompat.R.drawable.abc_ic_ab_back_mtrl_am_alpha)
                .title("图片")
                .titleColor(Color.WHITE)
                .titleBgColor(Color.parseColor("#25bf7f"))
                .cropSize(1, 1, 800, 480)
                .needCrop(false)
                // 第一个是否显示相机
                .needCamera(false)
                // 最大选择图片数量
                .maxNum(5)
                .build();

        ImgSelActivity.startActivity(this, config, REQUEST_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE && resultCode == RESULT_OK && data != null) {
            List<String> pathList = data.getStringArrayListExtra(ImgSelActivity.INTENT_RESULT);

            for (String path : pathList) {
                images.add(path);
            }
            adapter.setImages(images);
//            File file2 = new File(images.get(0));
//            FileUtilsOld.formatFileSizeToString(file2.length());

        }
    }

    /**
     * 压缩图片
     *
     * @param images
     * @return
     */
    private List<String> compressImages(List<String> images) {
        List<String> newImages = new ArrayList<>();
        for (int i = 0; i < images.size(); i++) {
            String newPath = FileUtils.createRootPath(this) + "/" + System.currentTimeMillis() + ".jpg";
            try {
                imageFactory.compressAndGenImage(images.get(i),
                        newPath, 100, false);
                newImages.add(newPath);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return newImages;
    }

    @Override
    protected void onRestart() {
        super.onRestart();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    /**
     * 删除图片
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void deleteImage(DeleteImageEvent event) {
        if (event.getPosition() != -1) {
            images.remove(event.getPosition());
            adapter.setImages(images);
        }

    }

    private void getTag() {
        String loginUrl = Constant.URL_GOAL + "issueStudent/selectIssueType";
        HashMap<String, String> map = new HashMap<>();
        map.put("token", GetUserInfo.getToken(context));
        map.put("studentId", GetUserInfo.getStudentId(context));

        OkHttpUtils.post().url(loginUrl).params(map).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e("E", e.toString());
            }

            @Override
            public void onResponse(String response, int id) {

                try {
                    JSONObject jsonObject = null;
                    jsonObject = new JSONObject(response);
                    int resultCode = jsonObject.getInt("code");

                    if (resultCode != 200) {
                        ToastUtil.showToast(context, jsonObject.getString("message"));
                        return;
                    }

                } catch (JSONException e) {

                }

                Log.e("T", response);

                Gson gson = new Gson();
                AskClassTags model = gson.fromJson(response, AskClassTags.class);
                if (model.isSuccess()) {
                    Log.e("T", response);
                    for (AskClassTags.DataBean item : model.getData()) {
                        textTag.add(item.getCourseName());
                    }
                    textTag.add(textTag.size(), "其他");
                    classAdapter.onlyAddAll(textTag);


                }
            }
        });


    }

    private void addQuestion() {

        if (issueObject.length() == 0) {
            Snackbar.make(sumbitBtn, "请选择标签", Snackbar.LENGTH_SHORT).show();
            return;
        } else if (problemContent.getText().toString().length() == 0) {
            Snackbar.make(sumbitBtn, "请描述问题", Snackbar.LENGTH_SHORT).show();
            return;
        }
        ProgressBarBlackUtil.loadShow(context);
        String loginUrl = Constant.URL_GOAL + "issueStudent/addIssue";
        HashMap map = new HashMap();
        map.put("issuePersonId", GetUserInfo.getStudentId(context));
        map.put("issueText", problemContent.getText().toString().trim());
        map.put("token", GetUserInfo.getToken(context));
        map.put("issueObject", issueObject);

        if (images.size() > 0) {
            //记录压缩图片所需要的时间
            long time1 = System.currentTimeMillis();
            Log.e("Time", time1 + "");
            List<String> newImages = compressImages(images);
            File file2 = new File(newImages.get(0));
            Log.e("Time","耗时：" + (System.currentTimeMillis() - time1) / 1000 + "s\n"
                    + "图片大小:"+FileUtils.formatFileSizeToString(file2.length())
                    + "图片位置:" + newImages.get(0));


            Map<String, File> files = new HashMap<>();
            for (int i = 0; i < newImages.size(); i++) {
                files.put("file" + i, new File(images.get(i)));
            }
            final long time3 = System.currentTimeMillis();
            Log.e("Time", "Http request: 0 " + time3);
            OkHttpUtils.post()
                    .url(loginUrl)
                    .files("files", files)
                    .params(map)
                    .build()
                    .connTimeOut(20000)
                    .writeTimeOut(20000)
                    .readTimeOut(20000)
                    .execute(new StringCallback() {
                        @Override
                        public void onError(Call call, Exception e, int id) {
//                        isFirst = true;
                            Log.e("E", e.toString());
                            ProgressBarBlackUtil.loadCancel();
                        }

                        @Override
                        public void onResponse(String response, int id) {
                            ProgressBarBlackUtil.loadCancel();

                            try {
                                JSONObject jsonObject = null;
                                jsonObject = new JSONObject(response);
                                int resultCode = jsonObject.getInt("code");

                                if (resultCode != 200) {
                                    ToastUtil.showToast(context, "提问失败！");
                                    ProgressBarBlackUtil.loadCancel();
                                    return;
                                } else {
                                    ToastUtil.showToast(context, "提问成功！");
                                    Log.e("Time", "Http response"+ (System.currentTimeMillis() - time3)/1000 + "s" );
                                    finish();
                                }

                            } catch (JSONException e) {

                            }
                        }
                    });
        } else {

            OkHttpUtils.post().url(loginUrl).params(map).build().execute(new StringCallback() {
                @Override
                public void onError(Call call, Exception e, int id) {
                    Log.e("E", e.toString());
                }

                @Override
                public void onResponse(String response, int id) {

                    try {
                        JSONObject jsonObject = null;
                        jsonObject = new JSONObject(response);
                        int resultCode = jsonObject.getInt("code");
                        ProgressBarBlackUtil.loadCancel();
                        if (resultCode != 200) {
                            ToastUtil.showToast(context, jsonObject.getString("message"));
                            return;
                        } else {
                            ToastUtil.showToast(context, "提交成功！");
                            finish();

                        }

                    } catch (JSONException e) {
                        Log.e("T", e.getMessage());
                    }

                    Log.e("T", response);

                }
            });
        }
    }

}
